package hu.tortavar2.server;

import hu.tortavar2.shared.Shop;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;

public class ShopDao {

	DatastoreService datastore;
	
	public ShopDao() {
		datastore = DatastoreServiceFactory.getDatastoreService();
	}
	
	public List<Shop> getRecentShops() {
		Query query = new Query(Shop.ENTITY_NAME);
		query.addSort(Shop.SHOP_NAME, SortDirection.ASCENDING);
		
		List<Shop> results = new ArrayList<Shop>();
		for (Entity result : datastore.prepare(query).asIterable()) {
			Shop shop = fromEntity(result);
			results.add(shop);
		}
		return results;
	}
	
	public void deleteShop(String encodedKey) {
		Key key = KeyFactory.stringToKey(encodedKey);
		datastore.delete(key);
	}
	
	public String AddShop(Shop shop) {
		Entity entity = new Entity(Shop.ENTITY_NAME);
		entity.setProperty(Shop.SHOP_NAME, shop.getShopName());
		entity.setProperty(Shop.SHOP_ADDRESS, shop.getShopAddress());
		entity.setProperty(Shop.SHOP_PHONE, shop.getShopPhone());
		datastore.put(entity);
		
		String encodedKey = KeyFactory.keyToString(entity.getKey());
		return encodedKey;
	}
	
	private Shop fromEntity(Entity result) {
		Shop shop = new Shop();
		shop.setShopName((String)result.getProperty(Shop.SHOP_NAME));
		shop.setShopAddress((String)result.getProperty(Shop.SHOP_ADDRESS));
		shop.setShopPhone((String)result.getProperty(Shop.SHOP_PHONE));
		
		if(shop.getKey() == null) {
			String encodedKey = KeyFactory.keyToString(result.getKey());
			shop.setKey(encodedKey);
		}
		return shop;
	}
}
